﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using FogOutlook.Plugins.Classes;

namespace FogOutlook {
	public partial class LoginForm : Form {
		public LoginForm() {
			InitializeComponent();
			System.Drawing.Bitmap bmp = Properties.Resources.FogOutlook;
			this.Icon = System.Drawing.Icon.FromHandle(bmp.GetHicon());
			foreach(KeyValuePair<string, BugTrackerBase> bt in PluginLoader.Plugins) {
				int pos = btType.Items.Add(bt.Value);
			}
			if(btType.Items.Count > 0)
				btType.SelectedIndex = 0;
			if(ThisAddIn.IsConnected) {
				loginBtn.Enabled = false;
			}
		}

		private void loginBtn_Click(object sender, EventArgs e) {
			if(ThisAddIn.IsConnected) {

			}
			else {
				if(btURL.Text.Length == 0) {
					MessageBox.Show("Please enter a URL to connect to.");
					btURL.Focus();
					return;
				}
				if(username.Text.Length == 0) {
					MessageBox.Show("Please enter a username.");
					username.Focus();
					return;
				}
				if(password.Text.Length == 0) {
					MessageBox.Show("Please enter a password");
					password.Focus();
					return;
				}
				Properties.Settings.Default.bttype = btType.Text; // Why doesn't it save with the data binding?
				if(ThisAddIn.TryConnect(username.Text, password.Text, btURL.Text, btType.SelectedItem.ToString())) {
					Properties.Settings.Default.Save();
					loginBtn.Enabled = false;
				}
				else {
					Properties.Settings.Default.Save();
					MessageBox.Show("Failed to connect");
				}
			}
		}

		private void okBtn_Click(object sender, EventArgs e) {
			if(!ThisAddIn.IsConnected) {
				if(MessageBox.Show("Continue without connecting? Only \"Report On FogBugz\" will be available (if selected)", "Not connected...", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.No) {
					DialogResult = DialogResult.None;
					return;
				}
			}
		}
	}
}
